﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MyNote.Data.Models;
using System.Security.Principal;
using MyNote.Helpers;

namespace MyNote.Controllers
{
    [ValidateInput(false)]
    public class NoteController : Controller
    {
        private IPrincipal _user;

        public NoteController(IPrincipal user)
        {
            _user = user;
        }
        
        [Authorize]
        public ActionResult Index(int? num)
        {
            if (!num.HasValue) num = 1;

            using (var context = new NoteModelContainer())
            {
                var name = _user.Identity.Name;
                var notes = from n in context.NoteSet
                            where n.Owner == name
                            select n;

                return ViewNotes(num.Value, notes);
            }
        }

        [HttpPost]
        public ActionResult FTS(FormCollection collection)
        {
            var terms = collection["ft_term"];
            if (string.IsNullOrEmpty(terms))
                throw new InvalidOperationException("请不要通过Url直接访问该页面!");

            var hits = MvcApplication.FullTextIndexer.DoFullTextSearch(terms);

            return View("Index", hits);
        }

        private ActionResult ViewNotes(int num, IQueryable<Note> notes)
        {
            num = num - 1;
            notes = notes.OrderByDescending(n => n.CreatedDate);
            var pagedNotes = notes.Skip(num * PagerSetting.RecordPerPage);
            pagedNotes = pagedNotes.Take(PagerSetting.RecordPerPage);

            ViewData["PagerSetting"] = new PagerSetting()
            {
                CurrentPage = num,
                PageSize = PagerSetting.DefaultPageSize,
                TotalRecords = notes.Count()
            };
            return View("Index", pagedNotes.ToArray());
        }

        [Authorize]
        public ActionResult Taged(string tag, int? num)
        {
            if (!num.HasValue) num = 1;

            using (var context = new NoteModelContainer())
            {
                var t = context.TagSet.Include("Notes").FirstOrDefault(ts => ts.Title == tag);
                if (t == null)
                    throw new InvalidOperationException(string.Format("没有标签为{0}的文章！", tag));

                ViewData["Tag"] = tag;
                return ViewNotes(num.Value, t.Notes.AsQueryable());
            }
        }

        [Authorize]
        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        [Authorize]
        public ActionResult Create(Note note)
        {
            if ( Session[MvcApplication.Constants.PENDING_CREATE_NOTE] != null )
                Session.Remove(MvcApplication.Constants.PENDING_CREATE_NOTE);

            using (var context = new NoteModelContainer())
            {
                note.Owner = _user.Identity.Name;
                context.AddToNoteSet(note);
                TagHelper.AddTagFromNote(note, context);
                context.SaveChanges();
            }

            return RedirectToAction("Index", "Note");
        }

        [Authorize]
        public ActionResult Edit(Guid id)
        {
            using (var context = new NoteModelContainer())
            {
                var note = context.NoteSet.First(n => n.Id == id);
                return View(note);
            }
        }

        [HttpPost]
        [Authorize]
        public ActionResult Edit(Note note)
        {
            using (var context = new NoteModelContainer())
            {
                var tobeEditing = context.NoteSet.Include("Tags").First(n => n.Id == note.Id);

                if (string.IsNullOrEmpty(tobeEditing.Owner))
                    tobeEditing.Owner = _user.Identity.Name;

                tobeEditing.Title = note.Title;
                tobeEditing.Description = note.Description;

                if (string.Compare(tobeEditing.Tag, note.Tag) != 0)
                {
                    tobeEditing.Tag = note.Tag;
                    TagHelper.AddTagFromNote(tobeEditing, context);
                }

                context.SaveChanges();

                return RedirectToAction("Details", "Note", new { id = note.Id });
            }
        }

        public ActionResult Details(Guid id)
        {
            using (var context = new NoteModelContainer())
            {
                var note = context.NoteSet.Include("Tags").First(n => n.Id == id);
                return View(note);
            }
        }

        public ActionResult Delete(Guid id)
        {
            using (var context = new NoteModelContainer())
            {
                var note = context.NoteSet.FirstOrDefault(n => n.Id == id);
                context.DeleteObject(note);
                context.SaveChanges();

                return RedirectToAction("Index");
            }
        }
    }
}
